package com.shortvedio.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shortvedio.base.mapper.*;
import com.shortvedio.base.model.dto.VedioContentDto;
import com.shortvedio.base.model.po.*;
import com.shortvedio.search.model.es.VideosContentDoc;
import com.shortvedio.search.service.VideosService;
import com.shortvedio.base.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VideosServiceImpl implements VideosService {

    @Autowired
    private UserLikeMapper userLikeMapper;

    @Autowired
    private SUserInfoMapper sUserInfoMapper;
    @Autowired
    private UserFavoritesMapper userFavoritesMapper;

    @Autowired
    private UserInterestMapper userInterestMapper;

    @Autowired
    private RestHighLevelClient highLevelClient;

    @Autowired
    private VideosContentMapper videosContentMapper;

    @Autowired
    private VideosAboutMapper videosAboutMapper;

    @Autowired
    private UserRelationshipsMapper userRelationshipsMapper;

    @Override
    public Result getLikeVedio(Long userId,Integer page,Integer size) {
        Integer start = (page-1)*size;
        List<VedioContentDto> vedioContentDtos = userLikeMapper.selectLikeList(userId,start,size);
        getOtherInfo(vedioContentDtos,userId);
        return Result.success(vedioContentDtos);
    }

    @Override
    public Result getRecommendVedioList(Long userId) {
        if (userId==null){
            userId=0l;
        }
        //通过数据库查询
        //获取喜欢类型的视频
        List<VedioContentDto> typeList = userInterestMapper.getTypeList(userId);
        Integer count = 6-typeList.size();
        //获取热门的视频
        List<VedioContentDto> hotVideos = videosContentMapper.getHotVideos();
        //获取其他类型的视频
        List<VedioContentDto> otherTypeList = userInterestMapper.getOtherTypeList(userId, count);
        List<VedioContentDto> vedioContentDtos = new ArrayList<>();
        vedioContentDtos.addAll(typeList);
        vedioContentDtos.addAll(hotVideos);
        vedioContentDtos.addAll(otherTypeList);
        getOtherInfo(vedioContentDtos,userId);
        return Result.success(vedioContentDtos);
    }

    @Override
    public Result getFavoritesVedioList(Long favoritesId, Integer page, Integer size,Long userId) {
        Integer start = (page-1)*size;
        log.info("favoritesId:{}",favoritesId);
        List<VedioContentDto> vedioContentDtos = userFavoritesMapper.selectFavoritesList(favoritesId, start, size);
        getOtherInfo(vedioContentDtos,userId);
        return Result.success(vedioContentDtos);
    }

    @Override
    public Result getSelfVdeioList(Long userId,Integer status) {
        List<VedioContentDto> vedioContentDtos = videosContentMapper.selectMyVideos(userId, status);
        getOtherInfo(vedioContentDtos,userId);
        return Result.success(vedioContentDtos);
    }

    @Override
    public Result getSearchVedio(String keyWord,Long userId) throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("vedio");
        // 2.准备DSL
        request.source()
                .query(QueryBuilders.matchQuery("all", keyWord));
        // 3.发送请求
        SearchResponse response = highLevelClient.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        List<VedioContentDto> vedioContentDtos = handleResponse(response);
        getOtherInfo(vedioContentDtos,userId);
        return Result.success(vedioContentDtos);

    }

    @Override
    public Result getHotVedio(Long userId,Integer page,Integer size) {
        if (userId==null){
            userId = 0l;
        }
        Integer start = (page-1)*size;
        List<VedioContentDto> vedioContentDtos = videosContentMapper.selectHotVideos(start, size);
        getOtherInfo(vedioContentDtos,userId);
        return Result.success(vedioContentDtos);
    }

    @Override
    public Result getTypeVedio(Long userId,Integer type, Integer page, Integer size) {
        Integer start = (page-1)*size;
        List<VedioContentDto> vedioContentDtos = videosContentMapper.selectTypeVideos(type, start, size);
        getOtherInfo(vedioContentDtos,userId);
        return Result.success(vedioContentDtos);
    }

    @Override
    public Result getOneVideos(Long videoId,Long userId) {
        VideosContent videosContent = videosContentMapper.selectById(videoId);
        VedioContentDto vedioContentDto = new VedioContentDto();
        BeanUtils.copyProperties(videosContent,vedioContentDto);
        List<VedioContentDto> vedioContentDtos = new ArrayList<>();
        vedioContentDtos.add(vedioContentDto);
        getOtherInfo(vedioContentDtos,userId);
        return Result.success(vedioContentDtos);
    }


    private void getOtherInfo(List<VedioContentDto> vedioContentDtos,Long userId){
        vedioContentDtos.forEach(vedioContentDto -> {
            Long videosId = vedioContentDto.getId();
            //获取用户信息
            LambdaQueryWrapper<SUserInfo> sUserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sUserInfoLambdaQueryWrapper.eq(SUserInfo::getUserId,vedioContentDto.getUserId());
            SUserInfo sUserInfo = sUserInfoMapper.selectOne(sUserInfoLambdaQueryWrapper);
            vedioContentDto.setHeadSrc(sUserInfo.getHeadSrc());
            vedioContentDto.setName(sUserInfo.getName());
            //获得视频相关的信息
            LambdaQueryWrapper<VideosAbout> videosAboutLambdaQueryWrapper = new LambdaQueryWrapper<>();
            videosAboutLambdaQueryWrapper.eq(VideosAbout::getVideosId,videosId);
            VideosAbout videosAbout = videosAboutMapper.selectOne(videosAboutLambdaQueryWrapper);
            //喜欢的数量
            vedioContentDto.setLikeCount(videosAbout.getLikeCount());
            //收藏数
            vedioContentDto.setFavoritesCount(videosAbout.getFavoritesCount());
            //获取评论数
            vedioContentDto.setCommentCount(videosAbout.getCommentsCount());
            //获取分享数
//            vedioContentDto.setShareCount(videosAbout.getShareCount());
            //获取查看数
            vedioContentDto.setLookCount(videosAbout.getLookCount());
            //设置是否点赞，是否收藏，是否关注等信息
            LambdaQueryWrapper<UserLike> userLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLikeLambdaQueryWrapper.eq(UserLike::getUserId,userId).eq(UserLike::getVideoId,videosId);
            UserLike userLike = userLikeMapper.selectOne(userLikeLambdaQueryWrapper);
            if (userLike!=null){
                vedioContentDto.setIsLike(1);
            }
            //收藏
            LambdaQueryWrapper<UserFavorites> userFavoritesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userFavoritesLambdaQueryWrapper.eq(UserFavorites::getVideoId,videosId).eq(UserFavorites::getUserId,userId);
            UserFavorites userFavorites = userFavoritesMapper.selectOne(userFavoritesLambdaQueryWrapper);
            if (userFavorites!=null){
                vedioContentDto.setIsFavories(1);
            }
            //关注
            LambdaQueryWrapper<UserRelationships> userRelationshipsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userRelationshipsLambdaQueryWrapper.eq(UserRelationships::getUserId,userId).eq(UserRelationships::getTargetUserId,vedioContentDto.getUserId());
            UserRelationships userRelationships = userRelationshipsMapper.selectOne(userRelationshipsLambdaQueryWrapper);
            if (userFavorites!=null){
                vedioContentDto.setIsRelation(1);
            }
//            vedioContentDto.setIsShare(1);

        });
    }



    private List<VedioContentDto> handleResponse(SearchResponse response) {
        // 解析响应
        SearchHits searchHits = response.getHits();
        // 1.获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜索到" + total + "条数据");
        // 2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 3.遍历
        List<VedioContentDto> videosContentDocList = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            VideosContentDoc videosContentDoc = JSON.parseObject(json, VideosContentDoc.class);
            VedioContentDto vedioContentDto = new VedioContentDto();
            BeanUtils.copyProperties(videosContentDoc,vedioContentDto);
            videosContentDocList.add(vedioContentDto);
        }
        return videosContentDocList;
    }
}
